<?php
namespace app\shop\model;
use app\common\model\CommonModel;
use app\common\model\PurchaseOrder;
use app\common\model\OrderActivity;
use app\common\model\OrderPayLog;
use app\common\model\OrderGoods;
use app\shop\model\GoodsModel;
use app\common\model\Activity;
use app\common\model\Category;
use app\common\model\Order;
use app\common\model\Stock;
use app\common\model\Goods;
use app\common\model\User;
use think\Session;
use think\Db;

class AddOrderModel extends CommonModel
{
	/**
    * 添加订单信息
    */
    public static function addOrder($info)
    {
        /*判断商品库存*/
        if(self::isStock($info['gid'],$info['number'],$info['imei'],$info['sn']) === false)
        {
            return back(config('state.STATUS_CODE_THREE'),'产品库存不足');
        }
        /*开启事物*/
        Db::startTrans();
        /*添加订单信息*/
        $Order['order_sn'] = $info['order_sn'];
        $Order['order_money'] = $info['pay_order'];
        $Order['actual_money'] = $info['pay_actual'];
        $Order['stay_money'] = $info['pay_await'];
        $Order['small_money'] = $info['pay_recall'];
        $Order['pay_type'] = $info['pay_type'];
        $Order['state'] = $info['pay_await']==0?1:0;
        $Order['admin_id'] = Session::get('admin.admin_id');
        $Order['shop_id'] = Session::get('admin.shop_id');
        $Order['clerk'] = $info['clerk'];
        $Order['shop_name'] = $info['shop_name'];
        $Order['user_sn'] = $info['uid'];
        $Order['username'] = $info['username'];
        $Order['nkname'] = $info['nkname'];
        $Order['phone'] = $info['phone'];
        $Order['spare_phone'] = $info['spare_phone'];
        $Order['remarks'] = $info['desc'];
        $Order['addtime'] = time();
        if(!$orderid = (new Order())->serOrder($Order))
        {
            Db::rollback();
			return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
        }
        /*添加订单商品信息*/
        $Stock  = new Stock();
        $OrderGoods = new OrderGoods();
        $where['s.state'] = 0;
        $where['s.period_time'] = ['>=',strtotime(date('Y-m-d',time()))];
        $field = 'g.category_id,g.cat_id,g.brand_name,g.memory_name,g.attribute_name,g.colour_name,g.marker,g.goods_sn,';
        $field .= 'g.goods_name,g.selling_price,g.trade_price,g.unit,s.stock_id,s.imei,s.sn,s.number,s.contract_sn,s.buying_price,';
        $field .= 'g.profit_bonus,g.turnover_bonus,g.goods_id';
        foreach($info['gid'] as $i=>$id)
        {
            $where['s.goods_id'] = $id;
            if($imei[$i])
            {
                $where['imei'] = $imei[$i];
            }
            if($sn[$i])
            {
                $where['sn'] = $sn[$i];
            }
            
            $stockCount = $Stock->stockCount($where);
            $goodsarray = [];
            $gnm = 0;
            for($j=0;$j<$stockCount;$j++)
            {
                $stockList = $Stock->stockList($where,$field,'s.stock_id','find');
                
                $gnm += $stockList['number'];
                if($gnm == $info['number'][$i])
                {
                    $goodsarray[] = $stockList;
                    /*扣除商品库存信息*/
                    if($Stock->updateStorage(['stock_id'=>$stockList['stock_id']],['number'=>0,'state'=>1]) === false)
                    {
                        Db::rollback();
                        return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
                    }
                    break;
                }
                if($gnm > $info['number'][$i])
                {
                    $num = $gnm - $info['number'][$i];
                    $stockList['number'] = $stockList['number'] - $num;
                    $goodsarray[] = $stockList;
                    /*扣除商品库存信息*/
                    if($Stock->updateStorage(['stock_id'=>$stockList['stock_id']],['number'=>$num]) === false)
                    {
                        Db::rollback();
                        return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
                    }
                    break;
                }
                $goodsarray[] = $stockList;
                /*扣除商品库存信息*/
                if($Stock->updateStorage(['stock_id'=>$stockList['stock_id']],['number'=>0,'state'=>1]) === false)
                {
                    Db::rollback();
                    return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
                }
            }
            
            foreach($goodsarray as $goods)
            {
                $profit_bonus = $goods['profit_bonus'];
                $turnover_bonus = $goods['turnover_bonus'];
                if($info['pricetype'][$i] == 0)
                {
                    $profit_t_money = round((intval(strval($goods['selling_price'] * 100)) - intval(strval($goods['buying_price'] * 100))) * intval($goods['number']) * intval($goods['profit_bonus']) / 10000,2);
                    $turnover_t_money = round(intval(strval($goods['selling_price'] * 100)) * intval($goods['number']) * intval($goods['turnover_bonus']) / 10000,2);
                    $goods_money = round(intval(strval($goods['selling_price'] * 100)) * intval($goods['number'])/100,2);
                    $profit_money = round((intval(strval($goods['selling_price'] * 100)) - intval(strval($goods['buying_price'] * 100))) * intval($goods['number'])/100,2);
                }else{
                    $profit_t_money = round((intval(strval($goods['trade_price'] * 100)) - intval(strval($goods['buying_price'] * 100))) * intval($goods['number']) * intval($goods['profit_bonus']) / 10000,2);
                    $turnover_t_money = round(intval(strval($goods['trade_price'] * 100)) * intval($goods['number']) * intval($goods['turnover_bonus']) / 10000,2);
                    $goods_money = round(intval(strval($goods['trade_price'] * 100)) * intval($goods['number'])/100,2);
                    $profit_money = round((intval(strval($goods['trade_price'] * 100)) - intval(strval($goods['buying_price'] * 100))) * intval($goods['number'])/100,2);
                }
                $cost_money = round(intval(strval($goods['buying_price'] * 100)) * intval($goods['number'])/100,2);
                $Goodsd['order_id']          = $orderid;
                $Goodsd['goods_id']          = $goods['goods_id'];
                $Goodsd['stock_id']          = $goods['stock_id'];
                $Goodsd['category_id']       = $goods['category_id'];
                $Goodsd['cat_id']            = $goods['cat_id'];
                $Goodsd['brand_name']        = $goods['brand_name'];
                $Goodsd['memory_name']       = $goods['memory_name'];
                $Goodsd['attribute_name']    = $goods['attribute_name'];
                $Goodsd['colour_name']       = $goods['colour_name'];
                $Goodsd['marker']            = $goods['marker'];
                $Goodsd['goods_sn']          = $goods['goods_sn'];
                $Goodsd['goods_name']        = $goods['goods_name'];
                $Goodsd['imei']              = $info['imei'][$i];
                $Goodsd['sn']                = $info['sn'][$i];
                $Goodsd['contract_sn']       = $goods['contract_sn'];
                $Goodsd['selling_price']     = $goods['selling_price'];
                $Goodsd['trade_price']       = $goods['trade_price'];
                $Goodsd['number']            = $goods['number'];
                $Goodsd['unit']              = $goods['unit'];
                $Goodsd['price_type']        = $info['pricetype'][$i];
                $Goodsd['buying_price']      = $goods['buying_price'];
                $Goodsd['profit_bonus']      = $goods['profit_bonus'];
                $Goodsd['turnover_bonus']    = $goods['turnover_bonus'];
                $Goodsd['profit_t_money']    = $profit_t_money<0?0:$profit_t_money;
                $Goodsd['turnover_t_money']  = $turnover_t_money<0?0:$turnover_t_money;
                $Goodsd['goods_money']       = $goods_money;
                $Goodsd['profit_money']      = $profit_money;
                $Goodsd['cost_money']        = $cost_money;
                if(!$OrderGoods->serOrderGoods($Goodsd))
                {
                    Db::rollback();
                    return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
                }
            }
        }
        /*添加订单活动信息*/
        if(array_key_exists('act_type',$info))
        {
            $where = [];
            switch($info['act_type'])
            {
                case 0:$where['activity_id'] = $info['manjian'];break;
                case 1:$where['activity_id'] = $info['manzhe'];break;
                case 2:$where['activity_id'] = $info['manzen'];break;
                case 3:$where['activity_id'] = $info['zhekou'];break;
            }
            if($where['activity_id'] != '')
            {
                $field = 'activity_id,act_type,act_name,yh_money,discount,zs_goods';
                $actarr = (new Activity)->ActivityList($where,'','find',$field);
                $activit['order_id'] = $orderid;
                $activit['activity_id'] = $actarr['activity_id'];
                $activit['act_type'] = $actarr['act_type'];
                $activit['act_name'] = $actarr['act_name'];
                $activit['yh_money'] = $actarr['yh_money'];
                $activit['discount'] = $actarr['discount'];
                $activit['zs_goods'] = $actarr['zs_goods'];
                if(!(new OrderActivity())->serOrderActivity($activit))
                {
                    Db::rollback();
                    return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
                }
            }
        }
        /*添加支付信息*/
        $payLog['order_id'] = $orderid;
        $payLog['pay_type'] = $info['pay_type'];
        $payLog['actual_money'] = $info['pay_actual'];
        $payLog['nkname'] = Session::get('admin.nkname');
        $payLog['addtime'] = time();
        if(!(new OrderPayLog())->serPayLog($payLog))
        {
            Db::rollback();
            return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
        }
        Db::commit();
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
    }
    /**
    * 判断商品库存情况
    */
    private function isStock($gid,$number,$imei,$sn)
    {
        $Stock = new Stock();
        $where['state'] = 0;
        $where['period_time'] = ['>=',strtotime(date('Y-m-d',time()))];
        foreach($gid as $i=>$id)
        {
            $where['goods_id'] = $id;
            if($imei[$i])
            {
                $where['imei'] = $imei[$i];
            }
            if($sn[$i])
            {
                $where['sn'] = $sn[$i];
            }
            $num = $Stock->stockNumber($where);
            if($num < intval($number[$i]))
            {
              return false;  
            }
        }
        return true;
    }
    /**
    * 搜索用户信息
    */
    public static function getUserList($info)
    {
        if(!$info['sreach'])
        {
            return back(config('state.STATUS_CODE_THREE'),config('state.STATUS_MSG_THREE'));
        }
        $where = [];
        switch($info['ty'])
        {
            case CommonModel::NUMBER_ONE:$where['username'] = ['like','%'.$info['sreach'].'%'];break;
            case CommonModel::NUMBER_TWO:$where['nkname'] = ['like','%'.$info['sreach'].'%'];break;
            case CommonModel::NUMBER_THREE:$where['phone'] = ['like','%'.$info['sreach'].'%'];break;
            case CommonModel::NUMBER_FOUR:$where['spare_phone'] = ['like','%'.$info['sreach'].'%'];break;
        }
        if(!$user = (new User())->userList($where,'user_id,user_sn'))
        {
			return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
		}
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'),$user);
    }
    /**
	* 获取商品列表
	*/
	public static function getGoodsList($info)
	{
		$goodslist = (new Goods())->getGoodsList(self::is_where($info),10,$info['page']);
        $Category = new Category();
        $Stock = new Stock();
        foreach($goodslist['data'] as $i=>$vo)
        {
            $goodslist['data'][$i]['category_id'] = $Category->getCategoryField(['category_id'=>$vo['category_id']],'category_name');
            $goodslist['data'][$i]['cat_id'] = $Category->getCategoryField(['category_id'=>$vo['cat_id']],'category_name');
            $goodslist['data'][$i]['gnumber'] = $Stock->stockNumber(['state'=>0]);
        }
		return $goodslist;
	}
    /**
    * 条件整理
    */
    private function is_where($info)
    {
        $where['shop_id'] = Session::get('admin.shop_id');
        /*产品子分类*/
		if($info['cat_id'] != CommonModel::NUMBER_ZERO)
		{
			$where['cat_id'] = $info['cat_id'];
		}
        /*产品分类*/
		if($info['category_id'] != CommonModel::NUMBER_ZERO)
		{
			$where['category_id'] = $info['category_id'];
		}
        /*已选中商品id*/
        if($info['gids'] != '')
        {
            $where['goods_id'] = ['NOT IN',$info['gids']];
        }
        /*关键字搜索*/
		if($info['sreach'])
		{
			$where['goods_name|abbreviation|goods_sn'] = ['like','%'.$info['sreach'].'%'];
		}
        return $where;
    }
    /**
    * 采购单信息整理
    */
    public static function purchaseList($id)
    {
        $info = GoodsModel::goodsInfo($id,true);
        $data['admin_id'] = Session::get('admin.admin_id');
		$data['shop_id'] = Session::get('admin.shop_id');
        $data['goods_name'] = $info['goods_name'];
		$data['category_name'] = $info['category_id'];
		$data['cat_name'] = $info['cat_id'];
		$data['brand_name'] = $info['brand_name'];
		$data['memory_name'] = $info['memory_name'];
		$data['attribute_name'] = $info['attribute_name'];
		$data['colour_name'] = $info['colour_name'];
		$data['marker'] = $info['marker'];
		$data['unit'] = $info['unit'];
		$data['addtime'] = time();
		if(!(new PurchaseOrder())->setPurchase($data))
		{
			return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
		}
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
    }
    /**
    * 搜索某一个商品
    */
    public static function ogoodsInfo($info)
    {
        $where = [];
        if($info['field'] == 'barcode')
        {
            $where['bar_code'] = $info['value'];
        }
        if($info['field'] == 'marker')
        {
            $where['marker|abbreviation'] = $info['value'];
        }
        if(!$goodsinfo = (new Goods())->goodsInfo($where))
		{
			return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
		}
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'),$goodsinfo);
    }
    /**
    * 获取活动信息
    * 满足 商品id 商品价格 商品数量 
    */
    public static function orderActivit($info)
    {
        /*整理数据*/
        $gids = explode(',',$info['gids']); /*商品id*/
        $prices = explode(',',$info['prices']); /*商品价格，根据收货类型不同*/
        $numbers = explode(',',$info['numbers']); /*商品数量*/
        
        $goods = [];
        /*订单总价*/
        $total_price = 0;
        foreach($prices as $i=>$price)
        {
            $total = intval(strval($price * 100)) * intval($numbers[$i]);
            $total_price += $total;
            $goods[$gids[$i]] = ['price'=>$total,'number'=>intval($numbers[$i])];
        }
        
        $Activity = new Activity();
        $time = time(); /*当前时间*/
        $where['start'] = ['<',$time];
        $where['end'] = ['>',$time];
        /*满减*/
        $where['act_type'] = 0;
        $where['mz_money'] = ['<',$total_price];
        $manjian = $Activity->ActivityList($where,'mz_money DESC','find');
        /*满折*/
        unset($where['mz_money']);
        $where['act_type'] = 1;
        $where['zs_goods'] = ['IN',$info['gids']];
        $data = $Activity->ActivityList($where);
        $manzhe = [];
        foreach($data as $vo)
        {
            $goodsact = $goods[$vo['zs_goods']];
            if(intval($vo['number']) <= $goodsact['number'])
            {
                $manzhe[] = $vo;
            }
        }
        /*满赠*/
        $where['act_type'] = 2;
        $data = $Activity->ActivityList($where);
        $manzen = [];
        foreach($data as $vo)
        {
            $goodsact = $goods[$vo['zs_goods']];
            if(intval($vo['mz_money']) <= $goodsact['price'])
            {
                $manzen[] = $vo;
            }
        }
        /*折扣*/
        $where['act_type'] = 3;
        unset($where['zs_goods']);
        $data = $Activity->ActivityList($where);
        $zhekou = [];
        foreach($data as $vo)
        {
            $i = 1;
            $goodsact = explode(',',$vo['zs_goods']);
            foreach($goodsact as $v)
            {
                if(!in_array($v,$gids))
                {
                    $i = 2;
                    break;
                }
            }
            if($i == 1)
            {
                $zhekou[] = $vo;
            }
        }
        return ['manjian'=>$manjian,'manzhe'=>$manzhe,'manzen'=>$manzen,'zhekou'=>$zhekou];
    }
    /**
    * 计算活动订单价格
    */
    public function countOrderPay($info)
    {
        /*整理数据*/
        $gids = explode(',',$info['gids']); /*商品id*/
        $prices = explode(',',$info['prices']); /*商品价格，根据收货类型不同*/
        $numbers = explode(',',$info['numbers']); /*商品数量*/
        /*活动信息*/
        $data = (new Activity())->ActivityList(['activity_id'=>$info['id']],'','find');
        /*订单总价*/
        $total_price = 0;
        foreach($prices as $i=>$price)
        {
            $total = intval(strval($price * 100)) * intval($numbers[$i]) / 100;
            $total_price += $total;
        }
        /*满减*/
        if($data['act_type'] == 0)
        {
            return $total_price - $data['yh_money'];
        }
        /*满折*/
        if($data['act_type'] == 1)
        {
            foreach($gids as $i=>$id)
            {
                if($id == $data['zs_goods'])
                {
                    $total = intval(strval($prices[$i] * 100)) * intval($numbers[$i]);
                }
            }
            $bfb = $total * $data['discount'] / 10000;
            return $total_price - round($bfb,2);
        }
        /*折扣*/
        if($data['act_type'] == 3)
        {
            $zsgoods = explode(',',$data['zs_goods']);
            foreach($gids as $i=>$id)
            {
                if(in_array($id,$zsgoods))
                {
                    $total += intval(strval($prices[$i] * 100)) * intval($numbers[$i]);
                }
            }
            $bfb = $total * $data['discount'] / 10000;
            return $total_price - round($bfb,2);
        }
        return round($total_price,2);
    }
}

